package personal.emailsender.server.service.impl;

import java.net.URL;
import java.util.logging.Logger;

import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

import personal.emailsender.server.service.EmailSendService;
import personal.emailsender.shared.data.EmailContent;
import personal.emailsender.shared.enums.EmailServer;

public class MandrillSendingServiceImpl implements EmailSendService {

	private static final Logger logger =
			Logger.getLogger(MandrillSendingServiceImpl.class.getSimpleName());
	private static final URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();

	@Override
	public boolean sendEmail(EmailContent emailContent) throws Exception {
		FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
	    fetchOptions.doNotValidateCertificate();
	    fetchOptions.setDeadline(10D);
	    HTTPRequest request = new HTTPRequest(
	    		new URL(EmailServer.MANDRILL.getServerUrl()), HTTPMethod.POST, fetchOptions);
	    String jsonPayload = formMandrillString(emailContent);
	    request.addHeader(new HTTPHeader("content-type", "application/json"));
	    request.addHeader(new HTTPHeader("content-length", "" + jsonPayload.getBytes().length));
        request.setPayload(jsonPayload.getBytes("UTF-8"));
        logger.info("Request before sending to Mandrill: " + request);
        return 200 == fetcher.fetch(request).getResponseCode();
	}

	protected static String formMandrillString(EmailContent emailContent) {
		String body = "{\"key\":\"%s\","
        		+ "\"message\": {"
        		+ "  \"html\":\"%s\","
        		+ "  \"subject\": \"%s\", "
        		+ "  \"from_email\": \"%s\", "
        		+ "  \"to\": [%s]}}";
        String toFormat = "{\"email\":\"%s\", \"type\":\"to\"}";
        StringBuilder toEmails = new StringBuilder();
        for (String receiverEmail : emailContent.getReceiverEmails()) {
        	if (toEmails.length() != 0) {
        		toEmails.append(", ");
        	}
        	toEmails.append(String.format(toFormat, receiverEmail));
        }
        return String.format(body, EmailServer.MANDRILL.getApiKey(),
        		emailContent.getContent(),
        		emailContent.getSubject(),
        		emailContent.getSenderEmail(),
        		toEmails);
	}
}
